import http from "wechat-http"
http.baseURL='https://live-api.itheima.net'
//响应拦截器
http.intercept.response = async function ({data,config}) {
  if(data.code===401){
    const app=getApp()
    if(config.url.includes('/refrenshToken')){
      const pageStack=getCurrentPages()
      const currentPage=pageStack.pop()
      const redirectURl=currentPage.route
      return wx.redirectTo({
        url: '/pages/login/index?redirectURL=/'+redirectURl,  
      })
    } 
    const res=await http({
      url:"/refreshToken",
      method:"POST",
      header:{
        Authorization:'Bearer '+app.refreshToken  
      }
    })
    if(res.code!==10000)return wx.utils.toast('更新token失败!')
   app.setToken('token', res.data.token)
   app.setToken('refreshToken', res.data.refreshToken)
    config=Object.assign(config,{
      header:{
        Authorization:'Bearer '+res.data.token
      }
    })
    return http(config)
  }
  return data
}
// 请求拦截器
http.intercept.request = (options) => {
  // 指定默认的头信息
  const defaultHeader= {}
  // 权限认证
  defaultHeader.Authorization = 'Bearer '+getApp().token
  // 合并头信息
  options.header = Object.assign({}, defaultHeader, options.header)
  // 拦截器处理后的请求参数
  return options
}
export default http
wx.http=http